package com.aismy.admin.service.impl;

import com.aismy.admin.entity.Article;
import com.aismy.admin.entity.ArticleComment;
import com.aismy.admin.entity.SysUser;
import com.aismy.admin.mapper.ArticleCommentMapper;
import com.aismy.admin.service.ArticleCommentService;
import com.aismy.admin.service.ArticleService;
import com.aismy.admin.service.UserService;

import com.aismy.admin.vo.CommentVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class ArticleCommentServiceImpl extends ServiceImpl<ArticleCommentMapper, ArticleComment> implements ArticleCommentService {

    private final UserService userService;
    private final ArticleService articleService;

    @Override
    @Transactional
    public void addComment(Long articleId, Long userId, String content, Long parentId) {
        // 检查文章是否存在
        Article article = articleService.getById(articleId);
        if (article == null || article.getStatus() == 2) {
            throw new RuntimeException("文章不存在");
        }

        // 如果是回复评论，检查父评论是否存在
        if (parentId != null) {
            ArticleComment parentComment = getById(parentId);
            if (parentComment == null || parentComment.getStatus() == 0) {
                throw new RuntimeException("回复的评论不存在");
            }
        }

        // 创建评论
        ArticleComment comment = new ArticleComment();
        comment.setArticleId(articleId);
        comment.setUserId(userId);
        comment.setContent(content);
        comment.setParentId(parentId);
        comment.setStatus(1);

        save(comment);

        // 更新文章评论数
        articleService.update()
                .setSql("comment_count = comment_count + 1")
                .eq("id", articleId)
                .update();
    }

    @Override
    @Transactional
    public void deleteComment(Long commentId, Long userId) {
        ArticleComment comment = getById(commentId);
        if (comment == null || comment.getStatus() == 0) {
            throw new RuntimeException("评论不存在");
        }

        // 只能删除自己的评论
        if (!comment.getUserId().equals(userId)) {
            throw new RuntimeException("无权删除此评论");
        }

        // 软删除评论
        comment.setStatus(0);
        updateById(comment);

        // 更新文章评论数
        articleService.update()
                .setSql("comment_count = comment_count - 1")
                .eq("id", comment.getArticleId())
                .update();
    }

    @Override
    public Page<CommentVO> getArticleComments(Long articleId, Integer page, Integer size) {
        // 获取评论列表（只获取顶级评论，不包括回复）
        Page<ArticleComment> commentPage = page(new Page<>(page, size),
                new LambdaQueryWrapper<ArticleComment>()
                        .eq(ArticleComment::getArticleId, articleId)
                        .isNull(ArticleComment::getParentId)
                        .eq(ArticleComment::getStatus, 1)
                        .orderByDesc(ArticleComment::getCreatedAt));

        return convertToVOPage(commentPage);
    }

    @Override
    public Page<CommentVO> getCommentReplies(Long commentId, Integer page, Integer size) {
        // 获取评论的回复列表
        Page<ArticleComment> replyPage = page(new Page<>(page, size),
                new LambdaQueryWrapper<ArticleComment>()
                        .eq(ArticleComment::getParentId, commentId)
                        .eq(ArticleComment::getStatus, 1)
                        .orderByAsc(ArticleComment::getCreatedAt));

        return convertToVOPage(replyPage);
    }

    private Page<CommentVO> convertToVOPage(Page<ArticleComment> commentPage) {
        List<ArticleComment> records = commentPage.getRecords();
        if (records.isEmpty()) {
            return new Page<CommentVO>().setTotal(0);
        }

        // 获取所有评论用户的信息
        List<Long> userIds = records.stream()
                .map(ArticleComment::getUserId)
                .distinct()
                .collect(Collectors.toList());

        Map<Long, SysUser> userMap = userService.listByIds(userIds).stream()
                .collect(Collectors.toMap(SysUser::getId, user -> user));

        // 获取父评论信息（如果有）
        List<Long> parentIds = records.stream()
                .map(ArticleComment::getParentId)
                .filter(id -> id != null)
                .distinct()
                .collect(Collectors.toList());

        Map<Long, ArticleComment> parentMap;
        if (!parentIds.isEmpty()) {
            parentMap = listByIds(parentIds).stream()
                    .collect(Collectors.toMap(ArticleComment::getId, comment -> comment));
        } else {
            parentMap = new HashMap<>();
        }

        // 转换为VO
        List<CommentVO> voList = records.stream().map(comment -> {
            CommentVO vo = new CommentVO();
            vo.setId(comment.getId());
            vo.setUserId(comment.getUserId());
            vo.setContent(comment.getContent());
            vo.setParentId(comment.getParentId());
            vo.setCreatedAt(comment.getCreatedAt());

            // 设置用户信息
            SysUser user = userMap.get(comment.getUserId());
            if (user != null) {
                vo.setUserName(user.getUsername());
                vo.setUserAvatar(user.getAvatar());
            }

            // 设置父评论信息
            if (comment.getParentId() != null) {
                ArticleComment parentComment = parentMap.get(comment.getParentId());
                if (parentComment != null) {
                    CommentVO parentVo = new CommentVO();
                    parentVo.setId(parentComment.getId());
                    parentVo.setContent(parentComment.getContent());

                    SysUser parentUser = userMap.get(parentComment.getUserId());
                    if (parentUser != null) {
                        parentVo.setUserName(parentUser.getUsername());
                    }

                    vo.setParentComment(parentVo);
                }
            }

            return vo;
        }).collect(Collectors.toList());

        Page<CommentVO> voPage = new Page<>();
        voPage.setRecords(voList);
        voPage.setTotal(commentPage.getTotal());
        voPage.setCurrent(commentPage.getCurrent());
        voPage.setSize(commentPage.getSize());

        return voPage;
    }
} 